package com.bigcat.gulimall.gulimallsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.bigcat.gulimall.common.entry.SkuEsModel;
import com.bigcat.gulimall.gulimallsearch.constant.EsConstant;
import com.bigcat.gulimall.gulimallsearch.service.ElasticSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Ather:Yuan
 * @Date:2021/1/4
 * @Desc:
 */
@Service
@Slf4j
public class ElasticSaveServiceImpl implements ElasticSaveService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    /**
     * 保存库存
     * @param esModelList
     * @return
     */
    @Override
    public boolean productStatusUp(List<SkuEsModel> esModelList) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : esModelList) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString()).source(JSON.toJSONString(skuEsModel), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        //是否失败，true:表示失败 false:表示成功
        boolean b = bulk.hasFailures();
        if (b){
            List<String> itemIds = Arrays.stream(bulk.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
            log.error("上架失败:{}",itemIds);
        }
        return !b;
    }
}
